//
//  LoginViewController.m
//  HTHappySale
//
//  Created by 创维海通 on 2017/9/18.
//  Copyright © 2017年 zxyywy. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterInfoViewController.h"
#import "CodeScanViewController.h"
#import "MainViewController.h"

//Request
#import "HTTPPromise+Login.h"

//Cell
#import "LoginCell.h"

//Tools
#import "UIViewController+KeyboardCorver.h"
#import "AppUtil.h"
#import "CellClearCache.h"


@interface LoginViewController ()<UITableViewDelegate,UITableViewDataSource,LoginSendDelegate>
{
    NSString *telephone;
    NSString *proof;
    int roleType;           //角色类型
}
@property (strong, nonatomic) IBOutlet UITableView *LoginTableView;
@property (nonatomic, strong) UIView *headerView;

@end

@implementation LoginViewController
#pragma mark -init
#define LoginIdentifyCell @"LoginCell"

#pragma mark -懒加载
- (UIView *)headerView
{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
//        _headerView.backgroundColor = HTCFQuickRGBColor(248, 64, 87);
        _headerView.backgroundColor = [UIColor whiteColor];
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_headerView.frame) / 2 - 70, 30, 140, 140)];
//        imageView.backgroundColor = [UIColor yellowColor];
        imageView.image = HTCFQuickImage(@"login");
        
        [_headerView addSubview:imageView];
    }
    return _headerView;
}

- (instancetype)init:(int)role
{
    if (self = [super init]) {
        roleType = role;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self addNavigationLeftView:@"" andType:1];
    [self addNavigationMiddleView:@"绑定手机号"];
    [self.navigationController setNavigationBarHidden:NO];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    //Xib
    UINib *nib = [UINib nibWithNibName:NSStringFromClass([LoginCell class])
                                bundle:[NSBundle mainBundle]];
    [_LoginTableView registerNib:nib forCellReuseIdentifier:LoginIdentifyCell];
    
//    HTCFUDFCache(kSignServiceKey,privateKey);
//    encryptionToken = privateKey;
    
    [self initTableView];
    [self addNotification];
}

- (void)initTableView
{
    _LoginTableView.tableFooterView = [[UIView alloc] init];
    _LoginTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _LoginTableView.tableHeaderView = self.headerView;
    _LoginTableView.scrollEnabled = NO;
}

#pragma mark -tableDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

#define cellIdentify @"cell"
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row != 2) {
        LoginCell *loginCell = [tableView dequeueReusableCellWithIdentifier:LoginIdentifyCell];
        loginCell = [CellClearCache clearCache:loginCell];
        
        [loginCell configureCell:indexPath.row];
        loginCell.delegate = self;
        loginCell.selectionStyle = UITableViewCellSelectionStyleNone;
        
        return loginCell;
    }else{
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
        
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
        }
        cell = [CellClearCache clearCache:cell];
        
        UIButton *submitBtn = [[UIButton alloc] initWithFrame:CGRectMake(40, 9.5, SCREEN_WIDTH - 80, 30)];
        [submitBtn addTarget:self action:@selector(dataRequest) forControlEvents:UIControlEventTouchUpInside];
        [submitBtn setBackgroundColor:HTCFQuickRGBColor(51, 190, 0)];
        
        [submitBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [submitBtn setTitle:@"登录并绑定" forState:UIControlStateNormal];
        submitBtn.layer.masksToBounds = YES;
        submitBtn.layer.cornerRadius = 10;
        
        [cell addSubview:submitBtn];
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForHeaderInSection:(NSInteger)section
{
    return 0;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -private

#pragma mark -loginDelegate
- (void)transmit{
    UITextField *teleText = [self.LoginTableView viewWithTag:100];
    telephone = teleText.text;
    
    if(!HTCFVerifyPhoneNumber(telephone)){
        [AppUtil showTipMessage:@"请输入正确11位手机号码"];
        return ;
    }
    NSDictionary *doctorParam = @{@"mobile":telephone};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:doctorParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:doctorParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }

    [HTTPPromise requesSendCodeParams:jsonData Success:^(id responseObj) {
        NSLog(@"%@",responseObj);
        if ([responseObj[@"ret"] intValue]!= 0) {
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)dataRequest{
    UITextField *proofText = [self.LoginTableView viewWithTag:101];
    proof = proofText.text;
    
    UITextField *teleText = [self.LoginTableView viewWithTag:100];
    telephone = teleText.text;
    
    if(!HTCFVerifyPhoneNumber(telephone)){
        [AppUtil showTipMessage:@"请输入正确11位手机号码"];
        return ;
    }
    
    if(!HTCFVerifyCode(proof)){
        [AppUtil showTipMessage:@"请输入正确验证码"];
        return ;
    }
    
    NSDictionary *doctorParam = @{@"mobile":telephone,@"verificationCode":proof};
    NSData *jsonData;
    
    if ([NSJSONSerialization isValidJSONObject:doctorParam])
    {
        NSError *error;
        jsonData = [NSJSONSerialization dataWithJSONObject:doctorParam options:NSJSONWritingPrettyPrinted error:&error];
        NSString *json =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"json data:%@",json);
    }
    
    __weak __typeof(self)weakSelf = self;
    [HTTPPromise requesBindMobileParams:jsonData Success:^(id responseObj) {
        __strong __typeof(weakSelf)strongSelf = weakSelf;
        NSLog(@"%@",responseObj);
        int successRet =[responseObj[@"ret"] intValue];

        if (successRet == 0) {
            [strongSelf saveMobile];
        }else{
            [AppUtil showTipMessage:responseObj[@"desc"]];
        }
    } failure:^(NSError *error) {
        NSLog(@"%@",error.userInfo);
    }];
}

- (void)saveMobile{
    HTCFUDFCache(kMobileKey,telephone);
    mobileStr = HTCFUDFGetValue(kMobileKey);
    roleType = [HTCFUDFGetValue(kRoleKey) intValue];
    
    NSLog(@"---------------------%d",roleType);
    if (roleType == -1) {
        RegisterInfoViewController *registerInfoVC = [[RegisterInfoViewController alloc] init];
        
        if (self.presentingViewController) {
            [self.navigationController presentViewController:registerInfoVC animated:YES completion:nil];
        }else{
            [self.navigationController pushViewController:registerInfoVC animated:YES];
        }
    }else{
        MainViewController *mainVC = [[MainViewController alloc] init];
        
        if (self.presentingViewController) {
            UIViewController *vc =  self;
            while (vc.presentingViewController) {
                vc = vc.presentingViewController;
            }
            NSLog(@"vc:========%@",vc);
            [vc dismissViewControllerAnimated:YES completion:nil];
        }else{
            [self.navigationController pushViewController:mainVC animated:YES];
        }
    }
}

#pragma mark -textFieldDelegate
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [[self view] endEditing:YES];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
